package com.banban.user.controller;

import com.alibaba.fastjson.JSON;
import com.banban.user.config.TaskProperties;
import com.banban.user.domain.*;
import com.banban.user.dto.DeepSeekDTO;
import com.banban.user.mapper.ConversationLogMapper;
import com.banban.user.mapper.SessionInfoMapper;
import com.banban.user.mapper.UserLoginRecordMapper;
import com.banban.user.mapper.UserProfileMapper;
import com.banban.user.service.ConversationSummarizeService;
import com.banban.user.service.PromptTemplateService;
import com.banban.user.service.TestService;
import com.banban.user.service.UserService;
import com.banban.user.util.DeepSeekSendMessage;
import com.banban.user.util.PushUtil;
import com.banban.user.util.RedisUtil;
import com.banban.user.util.UniqueIDUtil;
import com.banban.user.vo.ConversationLogVO;
import com.banban.user.vo.DataResult;
import com.banban.user.vo.PromptTemplateVO;
import com.banban.user.vo.UserProfileDetailVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Value("${promptTemplateId}")
    private String promptTemplateId;

    @Resource
    private TestService testService;

    @Autowired
    private DeepSeekSendMessage deepSeekSendMessage;

    @Autowired
    private PromptTemplateService promptTemplateService;

    @Autowired
    private TaskProperties taskProperties;

    @Resource
    private ConversationLogMapper conversationLogMapper;

    @Resource
    private UserProfileMapper userProfileMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private PushUtil pushUtil;

    @Resource
    private UserLoginRecordMapper loginRecordMapper;

    @Resource
    private SessionInfoMapper sessionInfoMapper;

    @Autowired
    private ConversationSummarizeService conversationSummarizeService;

    private static final String BANBAN_USER_MESSAGE = "BANBAN_USER_MESSAGE_";

    @PostMapping("/upload")
    public DataResult upload(@RequestParam("file")MultipartFile multipartFile) throws IOException {
        String url = testService.upload(multipartFile);
        return DataResult.success(url);
    }

    @PostMapping("/deepseek")
    public DataResult deepseek(@RequestBody DeepSeekDTO dto) throws IOException {
        String response = deepSeekSendMessage.getResponse(dto.getPrompt(),dto.getSystem());
        return DataResult.success(response);
    }

    @PostMapping("/chatWithTemplate")
    public DataResult chatWithTemplate(@RequestBody DeepSeekDTO dto) throws IOException {
        String response = testService.chatWithTemplate(dto.getPromptList().toString(),dto.getTemplateId());
        return DataResult.success(response);
    }

    @GetMapping("/getTime")
    public DataResult getTime() throws IOException {
//        System.out.println("Fixed Rate Task executed at: " + System.currentTimeMillis());
        List<String> createBys = conversationLogMapper.selectCreateBy(taskProperties.getDay());
        log.info("createBys ======={}", createBys);
        if (createBys.isEmpty()){
            return DataResult.fail("没数据");
        }
        PromptTemplateVO promptById = promptTemplateService.getPromptById(promptTemplateId);
        String promptTemplate = promptById.getPrompt();
        for (String createBy : createBys) {
            List<ConversationLog> list = conversationLogMapper.selectByUserId(createBy,taskProperties.getDay());
            List<ConversationLogVO> vos = new ArrayList<>();
            if (!list.isEmpty()){
                for (ConversationLog conversationLog : list) {
                    ConversationLogVO vo = new ConversationLogVO();
                    BeanUtils.copyProperties(conversationLog,vo);
                    vos.add(vo);
                }
                String prompt = vos.toString();
                //调用大模型
                String response = deepSeekSendMessage.getResponse(prompt, promptTemplate);
                if (StringUtils.isNotEmpty(response)){
                    List<UserProfileDetailVO> userProfileDetailVOS = JSON.parseArray(response, UserProfileDetailVO.class);
                    for (UserProfileDetailVO userProfileDetailVO : userProfileDetailVOS) {
                        UserProfile userProfile = new UserProfile();
                        BeanUtils.copyProperties(userProfileDetailVO,userProfile);
                        userProfile.setUserId(createBy);
                        //直接新增
                        userProfile.setId(String.valueOf(UniqueIDUtil.generateId()));
                        userProfileMapper.insert(userProfile);
                    }
                }
            }
        }
        return DataResult.success();
    }

    @GetMapping("/delete")
    public DataResult delete(){
        List<Map<String, Object>> duplicates = userProfileMapper.selectByCondition();

        // 遍历重复记录，删除旧的记录
        for (Map<String, Object> duplicate : duplicates) {
            String userId = (String) duplicate.get("user_id");
            String field = (String) duplicate.get("field");
            String value = (String) duplicate.get("value");
            LocalDateTime maxUpdateTime = (LocalDateTime) duplicate.get("max_update_time");

            QueryWrapper<UserProfile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId)
                    .eq("field", field)
                    .eq("value", value)
                    .lt("update_time", maxUpdateTime);

            int deleted = userProfileMapper.delete(queryWrapper);
            System.out.println("Deleted " + deleted + " duplicate rows for user_id: " + userId + ", field: " + field + ", value: " + value);
        }
        return DataResult.success();
    }

    @GetMapping("/testSummary")
    public DataResult testSummary(){
        List<String> createBys = conversationLogMapper.selectCreateByYesterday();
        if (createBys.isEmpty()){
            return DataResult.fail("无数据");
        }

        String promptTemplate = "你是一位优秀的会话总结分析人员，请根据用户输入的对话信息，精准归纳为一句话，尽量包含对话内容的全部重要信息，内容不要太长，50字以内即可";
        for (String createBy : createBys) {
            List<ConversationLog> list = conversationLogMapper.selectByUserIdYesterday(createBy);
            List<ConversationLogVO> vos = new ArrayList<>();
            if (!list.isEmpty()) {
                for (ConversationLog conversationLog : list) {
                    ConversationLogVO vo = new ConversationLogVO();
                    BeanUtils.copyProperties(conversationLog, vo);
                    vos.add(vo);
                }
                String prompt = vos.toString();
                //调用大模型
                String response;
                try {
                    response = deepSeekSendMessage.getResponse(prompt, promptTemplate);
                } catch (IOException e) {
                    continue;
                }
                ConversationSummarize summer = new ConversationSummarize();
                summer.setUserId(createBy);
                summer.setContent(response);
                summer.setDateTime(LocalDate.now().minusDays(1));
                conversationSummarizeService.save(summer);
            }
        }
        return DataResult.success();
    }

    @GetMapping("/testSetUserProfile")
    public DataResult testSetUserProfile(){
        List<SysUser> list = userService.list();
        if (list != null && !list.isEmpty()) {
            for (SysUser sysUser : list) {
                String userId = sysUser.getId();
                List<UserProfile> userProfiles = userProfileMapper.selectByUserId(userId);
                if (userProfiles != null && !userProfiles.isEmpty()){
                    Map<String, String> map = new HashMap<>();
                    for (UserProfile userProfile : userProfiles) {
                        map.put(userProfile.getField(), userProfile.getValue());
                    }
                    redisUtil.set(BANBAN_USER_MESSAGE + userId, map);
                }
            }
        }
        return DataResult.success();
    }

    @PostMapping("/testPush")
    public DataResult testPush(@RequestBody Map<String, String> map){
        pushUtil.push(map.get("cid"),map.get("title"),map.get("content"));
        return DataResult.success();
    }

    @GetMapping("/testMsg")
    public DataResult testMsg(String[] userIdo){
//        List<String> userIds = loginRecordMapper.selectUserIdByTime(day);
        List<Map<String,String>> list = new ArrayList<>();
        List<String> userIds = Arrays.asList(userIdo);
        if (userIds != null && !userIds.isEmpty()) {
            for (String userId : userIds) {
                SysUser user = userService.getById(userId);
                if (user==null){
                    continue;
                }
                String nickName = user.getNickName();
                LambdaQueryWrapper<SessionInfo> lqwSession = new LambdaQueryWrapper<>();
                lqwSession.eq(SessionInfo::getUserId, userId);
                lqwSession.orderByDesc(SessionInfo::getCreateTime);
                lqwSession.last("limit 1");
                SessionInfo sessionInfo = sessionInfoMapper.selectOne(lqwSession);
                String sessionId = sessionInfo.getSessionId();
                LambdaQueryWrapper<ConversationLog> lqwConversationLog = new LambdaQueryWrapper<>();
                lqwConversationLog.eq(ConversationLog::getSessionId, sessionId);
                List<ConversationLog> conversationLogs = conversationLogMapper.selectList(lqwConversationLog);
                String response;
                String systemMessage = "我们开发了一款名为伴伴的陪伴类的手机应用app，为了提高用户粘性，需要针对用户昨天与大模型交互的记录生成一段提醒或者挽留类的推送消息，类似'还记得你上次说要XXXX（上次聊天核心内容），后来怎么了，我还想着这件事呢'这种话术，不超过50字，主旨在提高用户粘性，让用户乐意点击推送内容进入app，仅输出对应话术即可，其他内容不要说";
                String prompt;
                StringBuilder sb = new StringBuilder();
                for (ConversationLog conversationLog : conversationLogs) {
                    sb.append("用户：").append(conversationLog.getUserMessage()).append("\n");
                    sb.append("大模型：").append(conversationLog.getAssistantMessage()).append("\n");
                }
                prompt = sb.toString();
                try {
                    response = deepSeekSendMessage.getResponse(prompt, systemMessage);
                } catch (IOException e) {
                    continue;
                }
                String title = "Hello，" + nickName;
                Map<String,String> map = new HashMap<>();
                map.put("userId",userId);
                map.put("nickName",nickName);
                map.put("title",title);
                map.put("content",response);
                list.add(map);
            }
        }
        return DataResult.success(list);
    }
}
